package com.mingjie.daydayup;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;


import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;


public class MainActivity extends AppCompatActivity {
    static ImageView iv;
    static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    iv.setImageBitmap((Bitmap) msg.obj);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = (ImageView) findViewById(R.id.iv_view);
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                try {

                    url = new URL("https://www.baidu.com/img/bd_logo1.png");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode() == 200) {
                        InputStream in = connection.getInputStream();
                        final Bitmap bitmap= BitmapFactory.decodeStream(in);
//                        Message msg=Message.obtain();
//                        msg.obj=bitmap;
//                        msg.what=1;
//                        handler.sendMessage(msg);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(bitmap);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        ).start();
    }
}
